package com.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author Tanyu
 * @Date 2020/6/1 15:19
 * @Description RedisConfig配置类，相当于配置了RedisTemplate、和StringRedisTemplate
 * @Version 1.0
 */
@Configuration
public class RedisConfig {

  @Autowired
  RedisConnectionFactory redisConnectionFactory;

  @Bean
  public RedisTemplate<String, Object> functionDomainRedisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
    return redisTemplate;
  }

  /*
   *设置redisTemplate序列化策略，否则在使用redisTemplate的时候在redis的客户端查看会出现乱码
   */
  private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate,
      RedisConnectionFactory factory) {
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setConnectionFactory(factory);
  }
}
